package net.zoneland.knowledge.utils;

import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * 设置行高.
 * @author zx
 */
public class CustomCellWriteHeightConfig extends SimpleRowHeightStyleStrategy {

    /**
     * 默认高度
     */
    private static final int DEFAULT_HEIGHT = 15;

    /**
     * 简单的行高.
     */
    private int defaultHeight;

    public CustomCellWriteHeightConfig(final Short headRowHeight, final Short contentRowHeight) {
        super(headRowHeight, contentRowHeight);
        this.defaultHeight = contentRowHeight;
    }

    /**
     * Sets the height of content
     *
     * @param row
     * @param relativeRowIndex
     */
    @Override
    protected void setContentColumnHeight(final Row row, final int relativeRowIndex) {
        final Iterator<Cell> cellIterator = row.cellIterator();

        final int maxHeight = IntStream.concat(
                        IntStream.of(defaultHeight),
                        StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                                        cellIterator, Spliterator.NONNULL | Spliterator.IMMUTABLE), false
                                )
                                .filter(cell -> cell.getCellTypeEnum() == CellType.STRING)
                                .map(Cell::getStringCellValue)
                                .mapToInt(value -> StringUtils.split(value, ExcelUtils.CONTENT_SPLIT_SYMBOL).length * DEFAULT_HEIGHT)
                )
                .max()
                .orElse(defaultHeight);

        row.setHeightInPoints((short) maxHeight);
    }
}
